package com.wjggy.core.common.util.preferences;

import java.util.HashMap;
import java.util.Map;

/**
 * 解析存储配置文件中得${...}
 * 改出作用是将以pre,post开头和结尾的字符串取出得到变量名，并中SystemGlobals中读取
 * @author xiaofan.yu
 * @version VariableExpander.java Nov 8, 2011 8:10:25 PMZ
 */
public class VariableExpander {

	private VariableStore variables;
	private String pre;
	private String post;

	private Map cache;
	
	public VariableExpander(VariableStore variables, String pre, String post)
	{
		this.variables = variables;
		this.pre = pre;
		this.post = post;
		cache = new HashMap();
	}
	public void clearCache()
	{
		cache.clear();
	}
	
	/**
	 * 传入配置属性进行解析获取值，改属性值必须是以构造方法中得pre开头和post结尾，否则将会返回自身
	 * @param source
	 * @return
	 */
	public String expandVariables(String source)
	{
		String result = (String)this.cache.get(source);
		if (source == null || result != null) {
			return result;
		}
		int fIndex = source.indexOf(this.pre);
		if (fIndex == -1) {
			return source;
		}
		StringBuffer sb = new StringBuffer(source);
		while (fIndex > -1) {
			int lIndex = sb.indexOf(this.post);
			int start = fIndex + this.pre.length();
			if (fIndex == 0) {
				String varName = sb.substring(start, start + lIndex - this.pre.length());
				sb.replace(fIndex, fIndex + lIndex + 1, this.variables.getVariableValue(varName));
			}
			else {
				String varName = sb.substring(start, lIndex);
				sb.replace(fIndex, lIndex + 1, this.variables.getVariableValue(varName));
			}
			fIndex = sb.indexOf(this.pre);
		}
		result = sb.toString();
		this.cache.put(source, result);
		return result;
	}
}
